package com.youlu.campus.wechat.facotrys;

import com.youlu.campus.wechat.service.WechatComplaintService;
import com.youlu.campus.wechat.service.impl.PlatformWeChatComplaintServiceImpl;
import com.youlu.campus.wechat.service.impl.PubKeyWechatComplaintServiceImpl;
import com.youlu.campus.wechat.utils.StringHashGenerator;
import com.youlu.campus.entity.WechatMerchantConfig;
import com.youlu.campus.service.wechat.enums.WechatMerchantConfigVerifyEnum;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: WechatComplaintServiceFacotry
 * @Date 2025/6/19
 * @author: su
 */
@Component
public class WechatComplaintServiceFacotry {

    /**
     * 容器用于存储 WechatComplaintService
     */
    private final Map<String, WechatComplaintService> singletonWechatComplaintService = new ConcurrentHashMap<>();


    /**
     * 获取微信商户 投诉服务
     *
     * @param config
     * @return
     */
    public WechatComplaintService getWechatComplaintService(WechatMerchantConfig config) {
        //获取配置唯一值
        String configMD5 = StringHashGenerator.generateMD5(config.toString());

        WechatComplaintService wechatComplaintService = singletonWechatComplaintService.get(config.getMerchantId());
        //判断 不为null 并且 配置唯一值相同 就返回
        if (wechatComplaintService != null && configMD5.equals(wechatComplaintService.getConfigMD5())) {
            return wechatComplaintService;
        }
        //获取锁资源 保证同步
        synchronized (this) {
            // 再次检查，避免在等待锁的过程中其他线程已经创建了实例
            wechatComplaintService = singletonWechatComplaintService.get(config.getMerchantId());
            if (wechatComplaintService != null && configMD5.equals(wechatComplaintService.getConfigMD5())) {
                return wechatComplaintService;
            }

            // 创建新的 WechatComplaintService
            wechatComplaintService = buildWechatComplaintService(config);
            singletonWechatComplaintService.put(config.getMerchantId(), wechatComplaintService);
            return wechatComplaintService;
        }
    }


    private WechatComplaintService buildWechatComplaintService(WechatMerchantConfig config) {
        //公钥模式
        if (WechatMerchantConfigVerifyEnum.PUBLIC_KEY.getValue().equals(config.getVerifyMode())) {
            return new PubKeyWechatComplaintServiceImpl.Builder().config(config).build();
        }
        //平台模式 默认
        return new PlatformWeChatComplaintServiceImpl.Builder().config(config).build();

    }

}
